<?php
/**
 * Created by jinqiang on 2024/7/24 11:50.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Controllers\Om;


use App\Http\Controllers\Controller;
use App\Http\Services\Om\InventoryService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\Finder\Finder;

class InventoryController extends Controller
{
    public function list(Request $request, InventoryService $inventoryService)
    {
        $t = microtime(true);
        $this->validate($request, [
            'page' => 'required',
            'limit' => 'required'
        ]);
        $param = $request->all();
        $res = $inventoryService->search($param);
        $res['t'] = microtime(true) - $t;
        return result($res);
    }

    public function proportion(Request $request, InventoryService $inventoryService)
    {
        $this->validate($request, [
            'type_no' => 'required'
        ]);
        $param = $request->all();
        $res = $inventoryService->getProportion($param['type_no']);
        return $res['code'] === 0 ? success("查询成功", $res['data']) : error($res['msg'], $res);
    }

    public function setProportion(Request $request, InventoryService $inventoryService)
    {
        $this->validate($request, [
            'data' => 'required'
        ]);
        $param = $request->all();
        $res = $inventoryService->setProportion($param['data']);
        return $res['code'] === 0 ? success("设置成功") : error($res['msg'], $res);
    }

    public function setArrivalDate(Request $request, InventoryService $inventoryService)
    {
        $this->validate($request, [
            'type_no' => 'required',
            'arrivaldate' => 'required'
        ]);
        $param = $request->all();
        $res = $inventoryService->setArrivalDate($param);
        return $res['code'] === 0 ? success("设置成功") : error($res['msg'], $res);
    }

    public function excelList(Request $request, InventoryService $inventoryService)
    {
        $user = auth()->guard("api")->user();
        $name = $user->name;
        $nameId = $user->id;
        $processKey = "INVENTORY_EXCEL_EXPORT_{$nameId}";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        $finder = new Finder();
        $files = $finder->files()->in(storage_path("cache/inventory"))->name("库存分配_{$name}*.xls");
        $data = [];
        $createTimeList = [];
        foreach ($files as $file) {
            $fileName = $file->getFilename();
            $createUser = preg_match("/库存分配_(.*?)_(\d{14})\.xls/is", $fileName, $d) ? $d[1] : "";
            $data[] = [
                'create_user' => $createUser,
                'create_time' => date('Y-m-d H:i:s', strtotime($d[2])),
                'name' => $fileName,
                'status' => ($cache['file']??"") == $fileName ? 0 : 1,
                'process' => ($cache['file']??"") == $fileName ? $cache['process'] : 100
            ];
            $createTimeList[] = strtotime($d[2]);
        }
        array_multisort($createTimeList, SORT_DESC, $data);
        return result(['data' => $data, 'cache' => $cache]);
    }

    public function exportCache()
    {
        $user = auth()->guard("api")->user();
        $nameId = $user->id;
        $processKey = "INVENTORY_EXCEL_EXPORT_{$nameId}";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        return result($cache);
    }

    public function exportData(Request $request)
    {
        $this->validate($request, [
            'is_subject' => 'required'
        ]);
        $param = $request->all();
        $user = auth()->guard("api")->user();
        $name = $user->name;
        $nameId = $user->id;
        //添加导出的任务进度
        $processKey = "INVENTORY_EXCEL_EXPORT_{$nameId}";
        if(Cache::get($processKey)){
            return error("添加失败, 最近一次导出计划还未完成");
        }
        $cTime = date('YmdHis');
        $filename = "库存分配_{$name}_{$cTime}.xls";
        $file = storage_path("cache/inventory/").$filename;
        $spreadsheet = new Spreadsheet();
        $writer = new Xlsx($spreadsheet);
        $writer->save($file);
        if(file_exists($file)){
            $cache = ['file' => $filename, 'process' => 0, 'param' => $param];
            Cache::put($processKey, $cache, Carbon::now()->addSeconds(60));
            $cmd = 'php '.base_path().'/artisan command:exportData --type=inventory --id='.$nameId.' >/dev/null 2>&1 &';
            ppopen($cmd);
            return success("添加成功", $cache);
        }else{
            return error("添加失败, 创建文件失败");
        }
    }
}
